﻿const express = require('express')
const fs = require('fs')
const router = express.Router()
const request = require('request');

const multer = require('multer')
const path = require('path')


const webconfig = require('./web.config')


function downloadFont(url,name,callback,errcallback){
    if (url.indexOf('http') === -1) {
        var sprit = url[0] === '/' ? '' : '/'
        url = webconfig.IMG + sprit + encodeURI(url)
    }
    var stream = fs.createWriteStream('./font/'+name+ '.ttf');
    
	request(url).pipe(stream).on('close', callback).on('error',errcallback); 
}

router.get('/upload', (req, res) => {
    // console.log(req.query,'下载字体文件')
	let url = req.query.key;
	let name = req.query.name;
	//console.log(`url: ${url}, name: ${name}`)
	if (url == undefined || name == undefined) {
		res.send(`url: ${url}, name: ${name},有个参数没有`)
	} else {
	try {
			downloadFont(url, name, function(){
				res.send('Success');
				console.log(name + '下载完毕');
			}, function() {
				res.send(`能不能走点心url: ${url}, name: ${name}`)
	
}) 
		} catch (error) {
			res.send(`url: ${url}, name: ${name},能不能走点心`)
		}
}
})


// 上传模型文件
var model = multer.diskStorage({
	destination: path.resolve('./public/model/'),
	filename: function (req, file, cb) {
		cb(null, file.originalname)
	}
})

// 定义上传的文件格式
var modelUpload = multer({ 
	storage: model
})
router.post('/upload/model', modelUpload.single('model'), (req, res, next)=>{
	modelUpload.single('model')(req, res , function (err) {
		if (err) res.send({code: -1, msg: '失败'})
		res.send({code: 1, msg: 'success'})
	})	
})


module.exports = router;